import {
	defineStore
} from "pinia";

// import { ref, computed } from "vue";


export const useAudio = defineStore("cs.audio", () => {

	// 创建新的音频实例并播放
	let audio = uni.createInnerAudioContext();
	
	let playingId = 0;
	let timespmt = 0;
	let isPlay = true;

	// 连接
	function playVoice(item) {
		// 连点判断，解决上述的第1个问题
		var time = new Date().getTime();
		if (time - this.timespmt <= 500) return;
		this.timespmt = time


		let cilckId = item.id //之前取得是当前播放地址
		let url = item.url

		if (!this.playingId) {
			this.playingId = cilckId

			// audio.src = url;
			// audio.play();

			downloadAudio(url);

			audio.onEnded(() => {
				// 播放完毕，清除音频链接
				console.log('播放完毕');
				this.isPlay = false;
				// this.playingId = ''

				// innerAudioContext.destroy();
			})

			audio.onCanplay(() => {
				console.log('音频可以播放');
				this.isPlay = true;
			})

			audio.onPause(() => {
				console.log('播放暂停');
				this.isPlay = false;
			})

			audio.onError((res) => {
				console.log('audio play error', res)
				this.isPlay = false;
				// innerAudioContext.destroy();
			})
		} else {

			if (!this.isPlay) { //在暂停状态
				if (this.playingId == cilckId) { //是同一音乐就继续播
					audio.stop()
					audio.play()
					this.isPlay = true
				} else { //不是同一音乐重置暂停状态,然后播放
					this.isPlay = true
					audio.stop()
					// audio.destroy(); // 销毁实例

					// audio = uni.createInnerAudioContext();
					downloadAudio(url);

					// audio.src = url
					// audio.play()

					this.playingId = cilckId

				}
			} else { //不在暂停状态
				if (this.playingId == cilckId) { //如果是同一地址，就暂停，改变暂停状态
					audio.stop()
					this.isPlay = false
				} else { //不是同一地址，就赋值，播放新的
					audio.stop()
					// audio.destroy(); // 销毁实例

					downloadAudio(url);

					// audio = uni.createInnerAudioContext();
					// audio.src = url
					// audio.play()

					this.playingId = cilckId

					this.isPlay = true
				}
			}
		}

		// if (audio) {
		// 	disconnect();
		// }
		// // 创建新的音频实例并播放
		// audio = uni.createInnerAudioContext();
		// audio.stop()
		// audio.src = url;
		// audio.play();

		// callback(audio);

	}



	let downloadTask = null
	//下载视频
	function downloadAudio(url) {
		//先取消之前的下载任务
		if (downloadTask) {
			downloadTask.abort();
		}

		downloadTask = uni.downloadFile({
			url: url,
			success: (res) => {
				if (res.statusCode === 200) {
					audio.src = res.tempFilePath;
					audio.obeyMuteSwitch = true;
					audio.play();
				}
			},
			fail: (err) => {

				this.isPlay = false
				console.error('下载失败', err);
			}
		});
	}

	//取消下载
	function cancelDownload() {
		if (downloadTask) {
			downloadTask.abort();
		}
	}


	// 暂停
	function disconnect() {
		if (audio) {
			this.isPlay = false;
			this.playingId = 0;
			audio.pause();
			audio.stop();
			// audio.destroy();
			// audio = null;
		}

	}

	// 监听退出
	uni.$on("user.logout", () => {
		disconnect();
	});

	return {
		playVoice,
		audio,
		isPlay,
		playingId,
		disconnect
	};
}, {
	unistorage: true, // 开启后对 state 的数据读写都将持久化
});